"""

 Views definition
 $Id: views.py 428 2011-06-20 14:20:05Z andre $

"""
from meta import *
from sqlalchemy import text
import os
import glob

def __viewsList():
    installDir=os.path.dirname(__file__)
    if installDir=='': installDir='.'
    views={}
    for file in glob.glob(os.path.join('%s/views' % installDir, '*.sql')):
        basename=os.path.basename(file)
        viewName=basename.replace('.sql', '')
        infile=open(file, 'r')
        views[viewName]=infile.read()
        infile.close()
    return views

viewsDict = __viewsList()

def dropView(viewName):
    trans=connection.begin()
    try:
        connection.execute(text('DROP VIEW %s CASCADE' % viewName))
        trans.commit()
    except:
        trans.rollback()


def createView(viewName):
    sql=viewsDict[viewName]
    trans=connection.begin()
    try:
        connection.execute((sql))
        trans.commit()
    except:
        trans.rollback()

def dropViews():
    for view in viewsDict.keys():
        print "Dropping %s..." % view
        dropView(view)

def createViews():
    for view in viewsDict.keys():
        print "Creating %s..." % view
        createView(view)
